package YamlHelper

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

type yamlRead struct {
	path string
}

func NewYamlRead() *yamlRead {
	return &yamlRead{}
}

func (y *yamlRead) Parse(path string, out interface{}) error {
	y.path = path
	return y.read(out)
}

func (y *yamlRead) read(out interface{}) error {
	path := fmt.Sprintf("%s", y.path)
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	err = yaml.Unmarshal(b, out)
	return nil
}

type yamlWrite struct{}

func NewYamlWrite() *yamlWrite {
	return &yamlWrite{}
}

func (y *yamlWrite) Out(out interface{}, fileName string) error {
	data, err := yaml.Marshal(out)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(fileName, data, 0777)
	if err != nil {
		return err
	}
	return nil
}
